<template>
  <div class="studentMain">
    <div class="public-header">
      <div class="public-header-ch">账户设置</div>
      <div class="public-header-en">ACCOUNT SETTING</div>
      <div class="public-header-line"></div>
    </div>
    <div class="student_center">
      <div class="bigbg">
        <!-- 修改头像 start -->
        <div class="peo" >
          <!-- 默认头像 -->
          <div v-if="headPictureUrl == ''"><img class="currentPhoto" src="../../static/image/icon-default-avatar.png" alt=""></div>
          <div v-else><img :src="headPictureUrl" id="avatar" class="currentPhoto"/></div>
          <el-button class="amend" type="text" @click="dialogHead = true">
            <img class="modifyLogoEdit" src="../../static/image/bianji1.png" alt="">
          </el-button>
          <el-dialog  title="修改图像" :visible.sync="dialogHead" width="30%">
            <div class="new-name">上传头像</div>
           <div class="upload-tip">
              <span class="inputIcon" @click="btnUploadClick()">只能上传jpg/png文件，且不超过2M</span>
              <el-upload
                class="upload-demo"
                ref="upload"
                action="/api/uploadPicture"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :auto-upload="false"
                :show-file-list="true"
                :on-change="handleAvatarChange"
                >
                <el-button size="small" type="primary" id="upLoadPhoto">点击上传</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div> -->
              </el-upload>
           </div>

            <!-- <div class="download">
              <p class="download-word">上传JPG.PN格式小于2M</p>
              <p class="download-input">
                <img src="../../static/image/shangchuan.png" alt="">上传文件
                <input type="file" id="file"></p>
            </div> -->
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="uploadPic" el-button-dialog class="dialo-save">保 存</el-button>
              <!-- <el-button type="primary" @click="dialogHead = false" el-button-dialog>保 存</el-button> -->
            </span>
        </el-dialog>
        </div>   
        <!-- 修改头像 ending -->
      </div>
      <div class="modify">
        <div class="modifyleft">
          <!-- 修改手机号码 start -->
          <el-button type="text" @click="showDialogNumberModal" ref="">
            <a><img src="../../static/image/icon-account-setting-mobile.png" alt="">修改手机号码</a>
          </el-button>
          <el-dialog title="修改手机号码" :visible.sync="dialognumber" width="30%">
             <el-form id="test" :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">                
               <el-form-item label="手机号修改" prop="number">
                <el-input v-model.number="ruleForm.number" placeholder="请输入新手机号码"></el-input>
              </el-form-item>
              <el-form-item label="手机验证码" prop="proving">
                <el-input type="number" v-model="ruleForm.proving" placeholder="请输入手机验证码">
                  <div slot="append" @click="sendCode()">发送验证码</div>
                  <!-- <template slot="append" @click="sendCode()">发送验证码</template> -->
                </el-input>
              </el-form-item>
              <el-form-item class="modifyPassLine">
                <el-button type="primary" @click="numberModifity('ruleForm')">保存</el-button>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
                <!-- <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                <el-button @click="resetForm('ruleForm')">取消</el-button> -->
              </el-form-item>              
            </el-form>
            <!-- <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="numberModifity">保 存</el-button>
              <el-button type="primary" @click="dialognumber = false">取 消</el-button>
            </span> -->

            <!-- <p class="new-account">手机号修改</p>
            <p class="new-input"><input type="text" placeholder="请输入新手机号码"></p>
            <p class="new-account">手机验证码</p>
            <p class="new-input"><input type="text" placeholder="请输入手机验证码"><button class="verification_code">发送验证码</button></p>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="dialognumber = false">保 存</el-button>
              <el-button type="primary" @click="dialognumber = false">取 消</el-button>
            </span> -->
          </el-dialog>
          <!-- 修改手机号码 ending -->
        </div>
        <div class="modifyright">
          <!-- 修改手机密码 start -->
          <el-button type="text" @click="showModifyPasswordDialog" ref>
            <a><img src="../../static/image/icon-account-setting-password.png" alt="">修改密码</a>
          </el-button>
          <el-dialog title="修改密码" :visible.sync="dialogpass" width="30%">
            <el-form :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
              <el-form-item label="旧密码" prop="old">
                <el-input type="password" v-model.number="ruleForm2.old" placeholder="请输入旧密码"></el-input>
              </el-form-item>
              <div class="clear"></div>
              <el-form-item label="密码" prop="pass">
                <el-input type="password" v-model="ruleForm2.pass" placeholder="请输入新密码" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPass">
                <el-input type="password" v-model="ruleForm2.checkPass" placeholder="请输入新密码确认" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item class="mobile-baocun">
                <el-button type="primary" @click="passwordModify()">保 存</el-button>
                <!-- <el-button @click="resetForm('ruleForm2')">取消</el-button> -->
              </el-form-item>

            </el-form>
             <!-- <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="passwordModify()">保 存</el-button>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
                <el-button type="primary" @click="dialogpass = false">保 存</el-button>
              </span> -->
          </el-dialog>          
          <!-- 修改密码 ending -->
        </div>        
      </div>      
      <!-- <hr> -->
      <div class="information">
        <div class="edit" ><img v-if="buttonType=='1'"  @click="editor(1)" src="/../static/image/bianji2.png"></div>  
      <div class="infor">  
        <!-- <p>手机：<input type="num" value="" v-model="mobile" :disabled="allInputDisable" /></p> -->
        <p>姓名：<el-input type="text" value="" v-model="name" :disabled="allInputDisable" class="peopleStyle"></el-input></p>
        <p>手机：<el-input type="num" value="" v-model="mobile" readonly ></el-input></p>
        <p>性别：<el-input type="text" value="" v-model="gender" :disabled="allInputDisable" class="peopleStyle"></el-input></p>
        <p>职位：<el-input type="text" value="" v-model="position" :disabled="allInputDisable" class="peopleStyle"></el-input></p>
        <p>年龄：<el-input type="num" value="" v-model="age" :disabled="allInputDisable" class="peopleStyle"></el-input></p>
      </div>
      <div class="information_preservation">
        <!-- <button v-if="buttonType=='2'" @click="conserve()">保存</button> -->
        <button v-if="buttonType=='2'"  @click="saveData()">保存</button>
      </div>
      </div>
      
      
    </div>
    
  </div>
</template>
<script>
  export default {
    data(){

	  //新手机号验证
	  let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
      var checkNumber = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('手机号不能为空'));
		}
		setTimeout(() => {
          if (!reg.test(this.ruleForm.number)) {
              callback(new Error('手机号码格式不正确'));
            } 
            callback();
        
        }, 500);
        
      };
      var checkProving = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('验证码不能为空'));
		}
		callback();
      };
      

      //判断两次密码输入
      
      var checkOld = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('旧密码不能为空'));
		}
		callback();
      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm2.checkPass !== '') {
            this.$refs.ruleForm2.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm2.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }

      //判断两次密码输入end

      return{
        //{"id":1,"mobile":"123456789","password":"","name":"孙康","isDdelete":0}
        mobile:'',
        name:'',
        gender:'',
        position:'',
        age:'',
        headPictureUrl:'',
        dialogHead: false,
        dialognumber:false,
        dialogpass:false,
        //两次密码输入
        
        ruleForm2: {
          pass: '',
          checkPass: '',
          old: '',
          number:'',
        },
        rules2: {
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
          old: [
            { validator: checkOld, trigger: 'blur' }
          ]
        },

        //手机号
        ruleForm: {
          number:'',
          proving:''
         
        },
        rules: {

          number: [
            { validator: checkNumber, trigger: 'blur' }
          ],
          proving: [
            { validator: checkProving, trigger: 'blur' }
          ]
        },

        // 输入框是否可编辑        
         buttonType:1,//编辑按钮状态
         refs:''
      }
    },

    computed:{
      "allInputDisable":function(){
        if(this.buttonType==1){
          return true
        }
        return false
      }
    },
    methods:{
      // 获取所有数据
      getAllData(){
        let data = {
          mobile: JSON.parse(sessionStorage.getItem('login')).mobile,
          name:JSON.parse(sessionStorage.getItem('login')).name,
          age:JSON.parse(sessionStorage.getItem('login')).age,
          gender:JSON.parse(sessionStorage.getItem('login')).gender,
          position:JSON.parse(sessionStorage.getItem('login')).position,
          headPictureUrl:JSON.parse(sessionStorage.getItem('login')).headPictureUrl,
        }
        this.$http.accountSetting(data,(successRes)=>{
        let userInfo = JSON.parse(sessionStorage.getItem('login'));
          	//console.log(userInfo)
        this.mobile = userInfo.mobile;
        this.name = userInfo.name;
        this.age = userInfo.age;
        this.gender = userInfo.gender;
        this.position = userInfo.position
        this.headPictureUrl = userInfo.headPictureUrl
         	console.log(successRes) 
        },(errorRes)=>{
          //console.log(errorRes);
          alert(errorRes.message);
          console.log(errorRes);
        })
      },

      // 编辑详情
      editor:function(type){
        switch(type){
          case 1:
          this.buttonType=2;
          break;
          case 2:
          this.buttonType=1;          
          break;
        }
         this.flag=false
        // this.isReadOnly = true;
      },
      input(){
        this.flag=true
      },
      // 资料修改保存 dialognumber
      saveData:function(){
        let data = {
            mobile:this.mobile,
            name:this.name,
            gender:this.gender,
            position:this.position,
            age:this.age,
        }
        this.$http.saccountModify(data,(succesRes)=>{
          if(succesRes.errCode == 0){
            let currentUserInfo = sessionStorage.getItem('login');
            let currentUserInfoObj = JSON.parse(currentUserInfo);
            currentUserInfoObj.mobile = this.mobile;
            currentUserInfoObj.name = this.name;
            currentUserInfoObj.gender = this.gender;
            currentUserInfoObj.position = this.position;
            currentUserInfoObj.age = this.age;
            let currentUserInfoStr = JSON.stringify(currentUserInfoObj);
            sessionStorage.setItem('login',currentUserInfoStr)
          }
            location.reload(); 
            console.log(succesRes)
        },(errorRes)=>{
			    // alert("信息修改失败")
          	console.log(errorRes)
        })
      },

      // 修改密码dialog
      showModifyPasswordDialog:function(){
        this.dialogpass = true;
        if(this.$refs.ruleForm2){
          console.log(this.$refs);
          this.$refs.ruleForm2.resetFields();
        }
      },
      // 密码修改 保存
      passwordModify:function(){
        let data = {
        //   mobile: this.mobile,
          mobile: JSON.parse(sessionStorage.getItem('login')).mobile,
          oldPwd: this.ruleForm2.old,
          newPwd: md5(this.ruleForm2.pass),
          confirm: md5(this.ruleForm2.checkPass)
          // newPwd: this.ruleForm2.pass,
          // confirm: this.ruleForm2.checkPass
        }
        this.$http.pwdModify(data,(res)=>{
          console.log(res)
          if(res.errCode == 0){
        	  this.dialognumber = false;
        	  sessionStorage.removeItem('login')
        	  this.$router.push('/');
            
          }

          alert("密码修改成功")
          console.log(res)
        },(errorRes)=>{
          alert("密码修改失败")
          console.log(errorRes)
        })
        this.$refs['ruleForm2'].resetFields();
      },

      // 点击修改手机号码
      showDialogNumberModal(){
        this.dialognumber = true;
        this.ruleForm.number = ''; // 重置手机号码
        this.ruleForm.proving = ''; // 重置验证码
        if(this.$refs.ruleForm){
          console.log(this.$refs)
          this.$refs['ruleForm'].resetFields();
        }

      },
      // 发送手机验证码
      sendCode:function(){
        //debugger
        // let data = {
          // mobile: this.ruleForm.number,
          //mobileCode: this.ruleForm.proving,
        // }
        this.$http.sendMobileCode(null,(res)=>{
          if(res.errCode == 0){
            alert("验证码发送成功，请查收");
          }else{
            alert("验证码发送失败");
          }
          console.log(res)
        },(errorRes)=>{
          //alert("验证码错误")
          console.log(errorRes)
        })
      },
	    // 手机号修改 保存
      numberModifity:function(formName){
        let data = {
          newMobile: this.ruleForm.number,
          mobileCode: this.ruleForm.proving
        }
        this.$http.mobileModify(data,(res)=>{
          alert("手机号修改成功")
          if(res.errCode == 0) {
            this.mobile = data.newMobile;
            let currentUserInfo = sessionStorage.getItem('login');
            let currentUserInfoObj = JSON.parse(currentUserInfo);
            currentUserInfoObj.mobile = this.mobile;
            console.log(currentUserInfoObj)
            let currentUserInfoStr = JSON.stringify(currentUserInfoObj);
            console.log(currentUserInfoStr)
            sessionStorage.setItem('login',currentUserInfoStr);
            this.dialognumber = false;
            this.$refs[formName].resetFields();
            
          }
          console.log(res);
        },(errorRes)=>{
          alert(errorRes.message)
          console.log(errorRes)
        })
      },

      /*
        上传头像
      */
      handleAvatarSuccess(res, file) {
          console.log(res,file);
          if (res.errCode == 0){
            //alert('头像上传成功');
            document.getElementById('avatar').setAttribute("src",res.data.headPictureUrl);
            document.getElementById('topHeaderPic').setAttribute("src",res.data.headPictureUrl);
            let currentUserInfo = sessionStorage.getItem('login');
            let currentUserInfoObj = JSON.parse(currentUserInfo);
            currentUserInfoObj.headPictureUrl = res.data.headPictureUrl;
            let currentUserInfoStr = JSON.stringify(currentUserInfoObj);
            sessionStorage.setItem('login',currentUserInfoStr)
          }else{
            alert('头像上传失败，请重试')
            
          }
      },
      beforeAvatarUpload(file) {
        console.log(file)
        const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      handleAvatarChange:function(file){
        console.log(file)
      },
      // 保存头像
      uploadPic:function(){
        this.$refs.upload.submit();
        this.dialogHead = false;

      },
      //触发按钮事件
      btnUploadClick:function(){
        document.getElementById('upLoadPhoto').click() 
      },
      // 重置
      resetForm:function(formName) {
    
        this.$refs[formName].resetFields();
        this.dialognumber = false;
      }

    },
    created(){

    },
    mounted(){
      this.getAllData();

    }
  }
</script>
